package common.web;

import common.CommonConstants;
import common.LiteralConstants;
import common.model.WebUser;
import common.service.EmailSender;
import common.util.DbUtil;
import common.util.FacesUtil;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author shousuke
 */
public class SignupController extends GenericRequestController implements Serializable {

    private WebUser user = null;

    public WebUser getUser() {
        if (user == null) {
            user = new WebUser();
        }
        return user;
    }

    /**
     * Prepares settings for adding a new WebUser
     * 
     * Pre-condition: None
     * Post-condition: New instance of webUser is set in controller
     * 
     * @return Navigation outcome: webUser_create
     */
    public String createSetup() {
        WebUser wu = (WebUser) FacesUtil.getSessionMapValue(CommonConstants.SSN_CUR_WEB_USER);
        if (wu != null) {
            FacesUtil.addErrorMessage("You are currently logged in as " + wu.getUsername() + ". Please log out prior to signing up for a new account.");
            return null;
        } else {
            return "signup";
        }
    }

    /**
     * Persists the webUser object
     * 
     * Pre-condition: webUser is available
     * Post-condition: webUser is persisted and added to session
     * 
     * @return Navigation outcome
     */
    public String create() {
        user.setLastLogin(new Date());
        boolean success = persist(user, "User");
        if (success) {
            Long activationCode = generateActivationCode(user);
            EmailSender smtpMailSender = new EmailSender();
            String[] emaillist = {"nojunkmai1@hotmail.com"};
            smtpMailSender.postMail(emaillist, "Email Sender Test", getMsgBody(user.getUsername(), activationCode), "suke.shou@gmail.com");
        }
        return "activate";
    }

    private String getMsgBody(String username, Long activationCode) {
        StringBuffer sb = new StringBuffer();
        sb.append("Click the following link to activate your account.");
        sb.append(LiteralConstants.NEW_LINE);
        sb.append("http://localhost:8080/MyRichFaces/public/activate2.faces?");
        sb.append("username");
        sb.append(LiteralConstants.EQUAL);
        sb.append(username);
        sb.append(LiteralConstants.AND);
        sb.append("code");
        sb.append(LiteralConstants.EQUAL);
        sb.append(activationCode);
        return sb.toString();
    }

    private Long generateActivationCode(WebUser user) {
        /* Activation code is derived from id * createddate(minute) + createddate(sec)
        of the user that is to be activated. */
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(user.getCreatedDate());
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return user.getId() * minute * 100 + second;
    }

    public String validateActivationCode() {
        String username = FacesUtil.getRequestParameter(CommonConstants.REQ_ACTVTN_USERNAME);
        String activationCode = FacesUtil.getRequestParameter(CommonConstants.REQ_ACTVTN_CODE);
        Map param = new HashMap();
        param.put("username", username);
        WebUser u = (WebUser) DbUtil.getSingleResult(getEntityManager(), "WebUser.findByUsername", param);
        String actualActivationCode = generateActivationCode(u).toString();
        if (actualActivationCode.equals(activationCode)) {
            FacesUtil.addSuccessMessage("Account Activation Completed");
        } else {
            FacesUtil.addErrorMessage("Account Activation Failed");
        }
        return null;
    }
}
